﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using blackhouse.BlackApart.Business.Apartments;
using blackhouse.BlackApart.Business;
using blackhouse.BlackApart.Web;
using blackhouse.BlackApart.Business.Opinions;
using blackhouse.Web;
using System.Globalization;
using blackhouse.JavaScript.JQuery;
using System.Configuration;
using blackhouse.BlackApart.Business.Reservations;
using System.IO;
using blackhouse.Web.FasterFiles;
using blackhouse.Aparts.Web.Modules;
using blackhouse.mojoPortalExtend.Breadcrumbs;

namespace blackhouse.Aparts.Web.Pages {
    public partial class DisplayOpinion : NonCmsBasePage {

        #region Fields

        private IApartmentGroup[] allGroups;
        private Factory factory = Factory.Instance();
        private StatisticsOpinion opinions;
        private IOpinionCategory[] opinionCategories;
        private int apartmentTypeId = 0;
        private IApartmentGroup apartmentType;
        private int opinionCountPerPage = 10;
        private int page = 1;
        private IEnumerable<IOpinion> displayOpinions;
        private float defaultCatValue = -1;
        private int reservationId;
        private Guid reservationGuid;
        private IWebReservation reservation;
        private BreadcrumbsAccess breadcrumbs;

        #endregion

        #region Event Handlers

        protected override void OnPreInit(EventArgs e) {
            this.AllowSkinOverride = true;
            HttpContext.Current.Items.Add("skin", "blackhouse");

            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            this.ReadInputParameters();
            this.SetInstance();
            this.rptSelectApartmentTypes.ItemDataBound += new RepeaterItemEventHandler(ItemDataBound_rptSelectApartmentTypes);
            this.rptOpinionCategories.ItemDataBound += new RepeaterItemEventHandler(ItemDataBound_rptOpinionCategories);
            this.rptCategories.ItemDataBound += new RepeaterItemEventHandler(ItemDataBound_rptCategories);
            this.rptOpinions.ItemDataBound += new RepeaterItemEventHandler(ItemDataBound_rptOpinions);
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            (this.Master.FindControl("divCenter") as Panel).Visible = false;
            this.AddJavaScript();
            this.PopulateControls();
            if (this.reservation != null)
                this.PopulateAddOpinionControls();
            this.SetSeo();
            this.SetBreadcrumb();
        }

        #endregion

        #region Methods

        private void AddJavaScript() {
            JQueryLibraries jql = new JQueryLibraries();
            jql.IncludeJQueryMultiSelect();
            jql.IncludeFileBasedOnJQuery("blackhouse.Aparts.Web.Scripts.displayOpinion.js,blackhouse.Aparts.Web");
            if (this.reservation != null) {
                jql.IncludeFileBasedOnJQuery("blackhouse.Aparts.Web.Scripts.displayAddOpinion.js,blackhouse.Aparts.Web");
                FasterFilesProvider ffp = new FasterFilesProvider();
                ffp.AddAfterScript(@"$(function(){
    showAddOpinion('" + this.reservation.ReservationNumber + @"');
});");
            }
        }

        private void ReadInputParameters() {
            Int32.TryParse(Request["addOpinion"], out this.reservationId);
            Guid.TryParse(Request["reservation"], out this.reservationGuid);
            Int32.TryParse(Request["addOpinion"], out this.reservationId);
            Int32.TryParse(Request[UrlUtils.ParameterApartmentTypeId], out this.apartmentTypeId);
            Int32.TryParse(Request[UrlUtils.ParameterPage], out this.page);
            if (page <= 0)
                page = 1;
        }

        private void SetInstance() {
            this.allGroups = this.factory.GetApartmentGroup().GetAllApartmentTypes();
            this.opinions = factory.GetStatisticsOpinion();
            if (this.apartmentTypeId > 0)
                this.opinions.SetFilterByApartmentType(apartmentTypeId);
            this.opinionCategories = factory.GetOpinionCategory().GetCategories();
            if (this.apartmentTypeId > 0)
                this.apartmentType = factory.GetApartmentGroup(this.apartmentTypeId);

            this.displayOpinions = WebUtils.CutToPage<IOpinion>(this.opinions.GetOpinions(), page, opinionCountPerPage);
            if (reservationId > 0) {
                this.reservation = factory.GetWebReservation(reservationId);
                if (this.reservation.ReservationId != this.reservationId || this.reservation.Guid != this.reservationGuid)
                    this.reservation = null;
            }
        }

        private void SetSeo() {
            PageProvider page = PageProvider.Instance();
            page.SetCanonicalUrl(UrlUtils.GetOpinionsUrl(factory.GetPreFolderEvaluation(), this.apartmentType, null, this.page));
            string title = GetGlobalResourceObject("Aparts", "opinionsTitle").ToString();
            if (this.apartmentType != null) title = " - " + this.apartmentType.Name;
            page.SetPageTitle(title);
            page.SetPageKeywords(GetGlobalResourceObject("Aparts", "opinionsKeys").ToString());
            page.SetPageDescription(GetGlobalResourceObject("Aparts", "opinionsDescription").ToString());
        }

        private void SetBreadcrumb() {
            this.breadcrumbs = new BreadcrumbsAccess();
            this.breadcrumbs.AddCrumb("Opinie gości", UrlUtils.GetOpinionsUrl(factory.GetPreFolderEvaluation(), null, null, this.page));
            if (this.apartmentType != null)
                this.breadcrumbs.AddCrumb("Apartament: " + this.apartmentType.ShortName, UrlUtils.GetOpinionsUrl(factory.GetPreFolderEvaluation(), this.apartmentType, null, this.page));
        }

        private void PopulateControls() {
            this.lblOpinionsCount.Text = this.opinions.BasedOnNumberOfOpinions().ToString();
            this.lblOpinionsCount2.Text = this.lblOpinionsCount.Text;
            this.lblPersonCount.Text = this.lblOpinionsCount.Text;
            this.lblAvgOp.Text = this.opinions.GetAverageRatingAsText();

            this.rptSelectApartmentTypes.DataSource = this.allGroups;
            this.rptSelectApartmentTypes.DataBind();
            if (this.apartmentType != null) {
                this.lblSelectedApartment.Text = this.apartmentType.ShortName;
                this.lblTitle.Text = GetGlobalResourceObject("Aparts", "opinionsAbout") + ": " + this.apartmentType.Name;
            }
            else {
                this.lblSelectedApartment.Text = GetGlobalResourceObject("Aparts", "allApartments").ToString();
                this.lblTitle.Text = GetGlobalResourceObject("Aparts", "opinionsAbout") + ": " + this.lblSelectedApartment.Text;
            }

            this.rptOpinionCategories.DataSource = this.opinionCategories;
            this.rptOpinionCategories.DataBind();

            this.PopulateNavigationForList();
            this.PopulateList();
        }

        private void PopulateAddOpinionControls() {
            this.pnlAddOpinion.Visible = true;
            this.pnlAddOpinionComplete.Visible = true;

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["DefaultOpinionCategoryValue"])) {
                if (!float.TryParse(ConfigurationManager.AppSettings["DefaultOpinionCategoryValue"], NumberStyles.Float, CultureInfo.GetCultureInfo("en-US"), out this.defaultCatValue))
                    this.defaultCatValue = -1;
            }

            this.txtFirstName.Text = this.reservation.Client.FirstName;
            this.txtLastName.Text = this.reservation.Client.LastName;
            this.hdnReservationId.Value = this.reservation.ReservationId.ToString();
            this.rptCategories.DataSource = this.opinionCategories;
            this.rptCategories.DataBind();

        }

        private void PopulateNavigationForList() {
            if (page > 1)
                this.lnkPrevOpinions.NavigateUrl = UrlUtils.GetOpinionsUrl(factory.GetPreFolderEvaluation(), this.apartmentType, null, page - 1);
            else
                this.lnkPrevOpinions.CssClass = this.lnkPrevOpinions.CssClass.ReplaceEx("red", "gray");
            this.lnkNextOpinions.NavigateUrl = UrlUtils.GetOpinionsUrl(factory.GetPreFolderEvaluation(), this.apartmentType, null, page + 1);
            if (this.page == 1)
                if (this.opinions.BasedOnNumberOfOpinions() > opinionCountPerPage)
                    this.lblOpinionsRange.Text = opinionCountPerPage.ToString();
                else
                    this.lblOpinionsRange.Text = this.opinions.BasedOnNumberOfOpinions().ToString();
            else {
                int endOf = opinionCountPerPage * page;
                if (endOf >= this.opinions.BasedOnNumberOfOpinions()) {
                    endOf = this.opinions.BasedOnNumberOfOpinions();
                    this.lnkNextOpinions.CssClass = this.lnkNextOpinions.CssClass.ReplaceEx("red", "gray");
                    this.lnkNextOpinions.NavigateUrl = "";
                }
                this.lblOpinionsRange.Text = (opinionCountPerPage * (page - 1) + 1).ToString() + " - " + endOf;
            }
        }

        private void PopulateList() {
            this.rptOpinions.DataSource = this.displayOpinions;
            this.rptOpinions.DataBind();
        }

        private void ItemDataBound_rptSelectApartmentTypes(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.AlternatingItem:
                case ListItemType.Item:
                    IApartmentGroup group = e.Item.DataItem as IApartmentGroup;
                    HyperLink link = e.Item.FindControl("lnkApartmentType") as HyperLink;
                    if (group != null && link != null) {
                        if (group.Id == this.apartmentTypeId) {
                            e.Item.Visible = false;
                            return;
                        }
                        link.ToolTip = group.Name;
                        link.NavigateUrl = UrlUtils.GetOpinionsUrl(factory.GetPreFolderEvaluation(), group, null, 1);
                        link.Text = group.ShortName;
                    }
                    break;
                case ListItemType.Header:
                    if (this.apartmentTypeId > 0) {
                        HyperLink link2 = e.Item.FindControl("lnkApartmentType") as HyperLink;
                        link2.NavigateUrl = UrlUtils.GetOpinionsUrl(factory.GetPreFolderEvaluation(), null, null, 1);
                    }
                    else {
                        e.Item.Visible = false;
                    }
                    break;
                default:
                    break;
            }
        }

        private void ItemDataBound_rptOpinionCategories(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.AlternatingItem:
                case ListItemType.Item:
                    IOpinionCategory category = e.Item.DataItem as IOpinionCategory;
                    Literal lblCategory = e.Item.FindControl("lblCategory") as Literal;
                    Literal lblCategoryValue = e.Item.FindControl("lblCategoryValue") as Literal;

                    if (category != null && lblCategory != null && lblCategoryValue != null) {
                        lblCategory.Text = category.Name;
                        if (!string.IsNullOrEmpty(category.NameContinued))
                            lblCategory.Text += " (" + category.NameContinued + ")";
                        lblCategoryValue.Text = this.opinions.GetCategoryAverageRatingAsText(category.CategoryId);
                    }

                    break;
                default:
                    break;
            }
        }

        private void ItemDataBound_rptCategories(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.AlternatingItem:
                case ListItemType.Item:
                    IOpinionCategory category = e.Item.DataItem as IOpinionCategory;
                    Panel pnlAddCat = e.Item.FindControl("pnlCat") as Panel;
                    Label lblCatName = e.Item.FindControl("lblCatName") as Label;
                    Label lblCatVal = e.Item.FindControl("lblCatVal") as Label;

                    if (category != null && lblCatName != null && lblCatVal != null) {
                        lblCatName.Text = category.Name;
                        if (!string.IsNullOrEmpty(category.NameContinued))
                            lblCatName.Text += " (" + category.NameContinued + ")";
                        if (defaultCatValue > 0)
                            lblCatVal.Text = this.defaultCatValue.ToString("F1", CultureInfo.GetCultureInfo("en-US"));
                        else
                            lblCatVal.Text = this.opinions.GetCategoryAverageRating(category.CategoryId).ToString("F1", CultureInfo.GetCultureInfo("en-US"));
                        pnlAddCat.Attributes.Add("catid", category.CategoryId.ToString());
                    }

                    break;
                default:
                    break;
            }
        }

        private void ItemDataBound_rptOpinions(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.AlternatingItem:
                case ListItemType.Item:
                    IOpinion opinion = e.Item.DataItem as IOpinion;
                    OpinionItem item = e.Item.FindControl("item") as OpinionItem;

                    if (opinion != null && item != null) {
                        if (e.Item.ItemIndex % 2 != 0)
                            item.CssClass += " b-gray1";
                        item.Opinion = opinion;
                        item.DataBind();
                    }

                    break;
                default:
                    break;
            }
        }

        #endregion

    }
}